package com.cl.bootws.listener;


import com.cl.bootws.message.*;
import com.cl.bootws.util.JsonUtil;
import jakarta.websocket.DecodeException;
import jakarta.websocket.Decoder;
import jakarta.websocket.EndpointConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

@Slf4j
public class WsMessageDecoder implements Decoder.Text<AbstractMessage> {

    @Override
    public AbstractMessage decode(String s) throws DecodeException {
        AbstractMessage message = JsonUtil.toBean(s, AbstractMessage.class);
        if (null == message) {
            throw new DecodeException(s, "解析消息失败");
        }
        String type = message.getType();
        MessageType messageType = MessageType.getMessageType(type);
        if (null == messageType) {
            throw new DecodeException(s, "解析类型失败");
        }
        message = switch (messageType) {
            case SYSTEM -> JsonUtil.toBean(s, SystemMessage.class);
            case PING -> JsonUtil.toBean(s, PingMessage.class);
            case PERSON -> JsonUtil.toBean(s, PersonMessage.class);
        };
        return message;
    }

    // 该方法判断消息是否可以被解码（转换）
    @Override
    public boolean willDecode(String s) {
        log.debug("检查消息：【" + s + "】是否可以解码");
        AbstractMessage message = JsonUtil.toBean(s, AbstractMessage.class);
        if (null == message) {
            return false;
        }
        String type = message.getType();
        MessageType messageType = MessageType.getMessageType(type);
        return !ObjectUtils.isEmpty(messageType);
    }

    @Override
    public void init(EndpointConfig endpointConfig) {
    }

    @Override
    public void destroy() {
    }
}
